#include "Mutex.hpp"
#include <unistd.h>

struct ThreadData
{
    ThreadData(std::string name,Mutex &lockp )
        : _name(name),
        _lockp(&lockp)
    {
    }

    Mutex *_lockp;
    std::string _name;
};

int cnt = 100;

void *Routine(void *ags)
{
    ThreadData *thd = static_cast<ThreadData *>(ags);

    while (1)
    {
        LockGuard lock(*thd->_lockp);
        if (cnt > 0)
        {
            usleep(1000);
            cnt--;
            printf("我是线程%s,cnt此时还剩%d\n", thd->_name.c_str(), cnt);
        }
        else
        {
            break;
        }
    }

    return nullptr;
}

int main()
{
    Mutex lock;
    pthread_t t1, t2, t3, t4;
    ThreadData *td1 = new ThreadData("thread 1", lock);
    pthread_create(&t1, NULL, Routine, td1);

    ThreadData *td2 = new ThreadData("thread 2", lock);
    pthread_create(&t2, NULL, Routine, td2);

    ThreadData *td3 = new ThreadData("thread 3", lock);
    pthread_create(&t3, NULL, Routine, td3);

    ThreadData *td4 = new ThreadData("thread 4", lock);
    pthread_create(&t4, NULL, Routine, td4);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    pthread_join(t4, NULL);

    return 0;
}